package com.clippick.clipboard;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.PowerManager;
import android.text.ClipboardManager;
import android.util.Log;

import com.clippick.api.GetApi;
import com.clippick.common.GlobalValue;
import com.clippick.common.Utils;
import com.clippick.database.HistoryDBAdapter;

@SuppressWarnings("deprecation")
/*
 * This class is created to get local system clipboard of content such as text
 * in order to send it to server. It does polling to compare every given time
 * that whether it is NEW COPIED TEXT or not.
 */
public class GetClipBoardThread extends Thread {
	// common
	private PollingService mParent;
	private Handler mHandler;

	// network available
	private ConnectivityManager manager;

	// let android do polling when screen is on to avoid battery
	// consumption
	private PowerManager power;

	// get system clipboard instance
	private ClipboardManager clipBoard;

	// dbManager
	HistoryDBAdapter dbManager;

	boolean isFirst = true;

	public GetClipBoardThread(PollingService parent, Handler handler) {

		// system clipboard
		clipBoard = parent.getSystemClipboard();

		dbManager = parent.getLocalDb();

		// network
		manager = (ConnectivityManager) parent
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mParent = parent;
		mHandler = handler;

		// get screen on/off instance
		power = (PowerManager) parent.getSystemService(Context.POWER_SERVICE);
	}

	/** Cancel task */
	public void cancel() {
		interrupt();
	}

	@Override
	public void run() {
		while (true) {
			if (power.isScreenOn())
				// doesn't poll with unauthorized clippick user
				if (!GlobalValue.USER_ID.equals("") && !GlobalValue.IS_UPDATING) {
					doTask();
				}
			try {
				Thread.sleep(2500);
			} catch (InterruptedException ignored) {

			}
		}
	}

	@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
	private void doTask() {
		GlobalValue.isOnInsertSync = false;
		boolean isNewClip = true;

		// clear local variable
		String clipboardText = "";

		if (clipBoard.hasText()) {
			clipboardText = clipBoard.getText().toString();
		}

		if (!GlobalValue.AppClip.equals(clipboardText)) {
			GlobalValue.AppClip = "";
		}

		// Log.i("clip", "GlobalValue.AppClip : " + GlobalValue.AppClip);
		// Log.i("clip", "GlobalValue.PrevApp : " + GlobalValue.PrevClip);
		// Log.i("clip", "clpboardText : " + clipboardText);

		if (GlobalValue.AppClip.equals("")
				&& !GlobalValue.PrevClip.equals(clipboardText)
				&& !clipboardText.equals("") && !clipboardText.equals("[img0]")
				&& !GlobalValue.getAppClip(mParent).equals(clipboardText)
				&& !GlobalValue.getAppClip(mParent).equals("")) {

			// check again Is it new clip?!
			try{
				for (String item : dbManager.getAllText()) {
					if (item.equals(clipboardText)) {
						isNewClip = false;
						return;
					}
				}
			}catch(Exception e){
				isNewClip = false;
				return;
			}

			if (isNewClip) {
				Log.i("clip",
						"new text clip inserted: " + clipboardText.toString());

				try {
					if (Utils.checkNetwokState(manager)) {
						GlobalValue.PrevClip = clipboardText;
						GetApi api = new GetApi(mParent);
						api.insertNodeNewClip(clipboardText, "0");
						mHandler.sendEmptyMessage(0);
					}
				} catch (NullPointerException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
